package com.ustcinfo.ishare.esCURD;

import com.ustcinfo.ishare.utils.Blog;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Shinelon on 2017/12/26.
 * 封装 ES 查询的 查询操作
 */
public class ESSearch {
    private static final Logger LOGGER = LoggerFactory.getLogger(ESSearch.class);

    /**
     * 判断一个index中的type是否有数据
     * @param indexName
     * @param type
     * @return
     * @throws Exception
     */
    public Boolean existDocOfType(TransportClient transportClient, String indexName, String type) throws Exception {
        SearchRequestBuilder builder = transportClient.prepareSearch(indexName).setTypes(type)
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                .setSize(1);
        SearchResponse response = builder.execute().actionGet();
        long docNum = response.getHits().getTotalHits();
        if (docNum == 0) {
            System.out.println("索引不存在或者无数据！");
            return false;
        }
        System.out.println("索引中有数据！");
        return true;
    }

    /**
     * 根据id 查询该文档是否存在
     * @param transportClient
     * @param indexName
     * @param type
     * @param id
     * @return
     */
    public boolean existsDocumentById(TransportClient transportClient,String indexName,String type,String id){
        GetResponse getResponse = transportClient.prepareGet(indexName,type,id).setOperationThreaded(false).execute().actionGet();
        if (getResponse.isExists()){
            System.out.println("该文档存在！");
            return true;
        }
        System.out.println("该文档不存在！");
        return false;
    }

    /**
     * 判断索引是否存在
     * @param transportClient
     * @param indexName
     * @return
     * @throws Exception
     */
    public Boolean existIndex(TransportClient transportClient, String indexName) {
        IndicesExistsRequest request = new IndicesExistsRequest(indexName);
        IndicesExistsResponse response = transportClient.admin().indices().exists(request).actionGet();
        if (!response.isExists()) {
            System.out.println("索引不存在！");
            return false;
        }
        System.out.println("索引存在！");
        return true;
    }

    /**
     * 查询所有 索引名 及其 索引相关信息
     * @param conn
     * @param indexName
     * @param type
     * @return
     */
    public String queryAllIndex(HttpURLConnection conn, String indexName, String type){
        BufferedReader br = null;
        String line = null;
        StringBuilder resultBuilder = new StringBuilder();
        try {
            if (conn.getResponseCode() != 200) {
//                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                return null;
            }
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            while ((line = br.readLine()) != null) {
                resultBuilder.append(line);
                resultBuilder.append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultBuilder.toString();
    }

    /**
     * 查询所有数据
     * @param transportClient
     * @param indexName
     * @param type
     * @param showNum   显示的条数，默认显示10条
     * @param sortField 排序字段
     * @param sortType  排序方式，0 升序，1 降序，默认降序
     */
    public List<String> queryAllDocument(TransportClient transportClient, String indexName, String type, int showNum, String sortField, int sortType){
        List<String> list = new ArrayList<>();
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        SearchResponse searchResponse = null;
        if (sortType==0){
            searchResponse = transportClient.prepareSearch(indexName,type)
                    .setQuery(queryBuilder).addSort(sortField, SortOrder.ASC).setSize(showNum).execute().actionGet();
        } else {
            searchResponse = transportClient.prepareSearch(indexName)
                    .setQuery(queryBuilder).addSort(sortField, SortOrder.DESC).setSize(showNum).execute().actionGet();
        }
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
            list.add(iterator.next().getSourceAsString());
        }
        return list;
    }

    /**
     * 根据 输入字段 和 值，精确查询
     * @param transportClient
     * @param queryField
     * @param queryFieldValue
     * @param indexName
     * @param type
     * @param showNum
     * @param sortField
     * @param sortType
     */
    public List<String> queryByTerms(TransportClient transportClient,String queryField,Object queryFieldValue,String indexName,String type,int showNum,String sortField,int sortType){
        List<String> list = new ArrayList<>();
        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery(queryField, queryFieldValue));
        SearchResponse searchResponse = null;
        if (sortType==0){
            searchResponse = transportClient.prepareSearch(indexName,type)
                    .setQuery(queryBuilder).addSort(sortField, SortOrder.ASC).setSize(showNum).execute().actionGet();
        } else {
            searchResponse = transportClient.prepareSearch(indexName,type)
                    .setQuery(queryBuilder).addSort(sortField, SortOrder.DESC).setSize(showNum).execute().actionGet();
        }
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
//            list.add(iterator.next().getSourceAsString());
            System.out.println(iterator.next().getSourceAsString());
        }
        return list;
    }

    /**
     * 单条件 模糊查询
     * @param transportClient
     * @param queryField
     * @param queryFieldValue
     * @param indexName
     * @param type
     * @param showNum
     * @param sortField
     * @param sortType
     * @return
     */
    public List<String> queryLikeBySingleCondition(TransportClient transportClient,String queryField,String queryFieldValue,String indexName,String type,int showNum,String sortField,int sortType){
        List<String> list = new ArrayList<>();
        SearchResponse searchResponse = null;
                WildcardQueryBuilder wBuilder = QueryBuilders.wildcardQuery(queryField, queryFieldValue);
        if (sortType==0){
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(wBuilder)
                    .addSort(sortField, SortOrder.ASC)
                    .setSize(showNum).setExplain(true)
                    .execute()
                    .actionGet();
        } else {
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(wBuilder)
                    .addSort(sortField, SortOrder.DESC)
                    .setSize(showNum).setExplain(true)
                    .execute()
                    .actionGet();
        }
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
//            list.add(iterator.next().getSourceAsString());
            System.out.println(iterator.next().getSourceAsString());
        }
        return list;
    }

    /**
     * 多条件 模糊查询（不建议使用，存在问题）
     * @param transportClient
     * @param conditionsMap
     * @param indexName
     * @param type
     * @param showNum
     * @param sortField
     * @param sortType
     * @return
     */
    public List<String> queryLikeByMultiConditions(TransportClient transportClient, Map<String,Object> conditionsMap, String indexName, String type, int showNum, String sortField, int sortType){
        List<String> list = new ArrayList<>();
        SearchResponse searchResponse = null;
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        for (String in : conditionsMap.keySet()) {
            String str = conditionsMap.get(in).toString();
            boolQueryBuilder.must(QueryBuilders.wildcardQuery(in,str));
        }
        if (sortType==0){
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(boolQueryBuilder)
                    .addSort(sortField, SortOrder.ASC)
                    .setSize(showNum).setExplain(true)
                    .execute()
                    .actionGet();
        } else {
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(boolQueryBuilder)
                    .addSort(sortField, SortOrder.DESC)
                    .setSize(showNum).setExplain(true)
                    .execute()
                    .actionGet();
        }
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
//            list.add(iterator.next().getSourceAsString());
            System.out.println(iterator.next().getSourceAsString());
        }
        return list;
    }

    /**
     * 查询 文档 总数
     * @param conn
     * @return
     */
    public int queryDocumentNum(HttpURLConnection conn){
        int i = 0;
        BufferedReader br = null;
        String line = null;
        StringBuilder resultBuilder = new StringBuilder();
        try {
            if (conn.getResponseCode() != 200) {
//                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                return 0;
            }
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            while ((line = br.readLine()) != null) {
                resultBuilder.append(line);
                resultBuilder.append('\r');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(resultBuilder.toString().substring(resultBuilder.toString().indexOf("\"count\"")+8,resultBuilder.toString().indexOf("\"_shards\"")-1));
    }

    /**
     * 范围查询
     * @param transportClient
     * @param queryField
     * @param from
     * @param to
     * @param indexName
     * @param type
     * @param showNum
     * @param sortField
     * @param sortType
     * @return
     */
    public List<String> queryByRange(TransportClient transportClient,String queryField,Object from,Object to,String indexName,String type,int showNum,String sortField,int sortType){
        List<String> list = new ArrayList<>();
        SearchResponse searchResponse = null;
        QueryBuilder queryBuilder = QueryBuilders.rangeQuery(queryField).gt(from).lt(to);
        if (sortType==0){
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(queryBuilder)
                    .addSort(sortField, SortOrder.ASC)
                    .setSize(showNum)
                    .execute()
                    .actionGet();
        } else {
            searchResponse = transportClient.prepareSearch(indexName).setTypes(type)
                    .setQuery(queryBuilder)
                    .addSort(sortField, SortOrder.DESC)
                    .setSize(showNum)
                    .execute()
                    .actionGet();
        }
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
//            list.add(iterator.next().getSourceAsString());
            System.out.println(iterator.next().getSourceAsString());
        }
        return list;
    }

    /**
     * 多条件灵活组合查询
     * @param conn
     * @param conditions
     * @param size
     * @return
     * @throws IOException
     */
    public String queryByConditions(HttpURLConnection conn,Map<String,Object> conditions,int from,int size){

        try {
            DataOutputStream wr = null;
            BufferedReader br = null;
            StringBuilder resultBuilder = new StringBuilder();
            String line = null;
            String queryJsonStr = "";
            if (conditions.size()>1){
                queryJsonStr = buildMultiStr(conditions,from,size);
            }else{
                queryJsonStr = buildSingleStr(conditions,from,size);
            }
            queryJsonStr = queryJsonStr.replace("\t","");
            queryJsonStr = queryJsonStr.replace("\n","");
            queryJsonStr = new String(queryJsonStr.getBytes("utf-8"),"utf-8");
            wr = new DataOutputStream(conn.getOutputStream());
            // 防止中文乱码
            wr.write(queryJsonStr.getBytes("utf-8"));
//            wr.writeBytes(queryJsonStr.getBytes());
            if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
            br = new BufferedReader(new InputStreamReader((conn.getInputStream()),"utf-8"));
            while ((line = br.readLine()) != null) {
                resultBuilder.append(line);
                resultBuilder.append('\r');
            }
            return resultBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
return "";
    }

    private static String buildSingleStr(Map<String,Object> conditions,int from,int size){
        String queryParamJson = "";
        String queryParamJson1 = "{\n" +
                "\t\"from\": "+from+",\n" +
                "\t\"size\":" + size + ",";
        String queryParamJson2 = "\"sort\": [\n" +
                "\t\t{\n" +
                "\t\t\t\"receiveTime\": {\n" +
                "\t\t\t\t\"order\": \"desc\"\n" +
                "\t\t\t}\n" +
                "\t\t}\n" +
                "\t]\n" +
                "}";

        if (conditions.isEmpty()){
            queryParamJson = queryParamJson1 + queryParamJson2;
        }else{
            if (conditions.containsKey("msgid")) {
                queryParamJson = queryParamJson1 +
                        "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"msgid\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("msgid") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("receiveTime")) {
                String times = (String) conditions.get("receiveTime");
                String startTime = times.substring(0, times.indexOf("-"));
                String endTime = times.substring((times.indexOf("-") + 1));
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"range\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"receiveTime\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"from\":" + startTime +",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"to\":" + endTime +",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"include_lower\": true,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"include_upper\": true,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("servCode")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"servCode\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("servCode") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }

            if (conditions.containsKey("resendFlag")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"resendFlag\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("resendFlag") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("receiveSystem")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"receiveSystem\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("receiveSystem") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("serviceState")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"serviceState\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("serviceState") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("sendSystem")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"sendSystem\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("sendSystem") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
            if (conditions.containsKey("connFlag")) {
                queryParamJson = queryParamJson1 + "\"query\": {\n" +
                        "\t\t\"bool\": {\n" +
                        "\t\t\t\"filter\": [\n" +
                        "\t\t\t\t{\n" +
                        "\t\t\t\t\t\"bool\": {\n" +
                        "\t\t\t\t\t\t\"must\": [\n" +
                        "\t\t\t\t\t\t\t{\n" +
                        "\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\"connFlag\": {\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"query\": \"" + conditions.get("connFlag") +"\",\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                        "\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t\t}\n" +
                        "\t\t\t\t\t\t],\n" +
                        "\t\t\t\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\t\t\t\"boost\": 1\n" +
                        "\t\t\t\t\t}\n" +
                        "\t\t\t\t}\n" +
                        "\t\t\t],\n" +
                        "\t\t\t\"disable_coord\": false,\n" +
                        "\t\t\t\"adjust_pure_negative\": true,\n" +
                        "\t\t\t\"boost\": 1\n" +
                        "\t\t}\n" +
                        "\t},"
                        + queryParamJson2;
            }
        }
        return queryParamJson;
    }

    private static String buildMultiStr(Map<String,Object> conditions,int from,int size) throws UnsupportedEncodingException {
        String queryParamJson = "";
        String queryParamJsons1 = "{\n" + "\t\"from\": "+from+",\n" + "\t\"size\": "+size+",\n" + "\t\"query\": {\n"
                + "\t\t\"bool\": {\n" + "\t\t\t\"filter\": [\n" + "\t\t\t\t{\n" + "\t\t\t\t\t\"bool\": {\n"
                + "\t\t\t\t\t\t\"must\": [\n" + "\t\t\t\t\t\t\t{\n" + "\t\t\t\t\t\t\t\t\"bool\": {\n"
                + "\t\t\t\t\t\t\t\t\t\"must\": [\n" + "\t\t\t\t\t\t\t\t\t\t{\n"
                + "\t\t\t\t\t\t\t\t\t\t\t\"bool\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\"must\": [\n"
                + "\t\t\t\t\t\t\t\t\t\t\t\t\t{\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"sign\": {\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \"0\",\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t\t\t],\n"
                + "\t\t\t\t\t\t\t\t\t\t\t\t\"disable_coord\": false,\n"
                + "\t\t\t\t\t\t\t\t\t\t\t\t\"adjust_pure_negative\": true,\n"
                + "\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
        String queryParamJsons0 = "";
        String queryParamJsons2 = "],\n" + "\t\t\t\t\t\t\t\t\t\"disable_coord\": false,\n"
                + "\t\t\t\t\t\t\t\t\t\"adjust_pure_negative\": true,\n" + "\t\t\t\t\t\t\t\t\t\"boost\": 1\n"
                + "\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t],\n"
                + "\t\t\t\t\t\t\"disable_coord\": false,\n" + "\t\t\t\t\t\t\"adjust_pure_negative\": true,\n"
                + "\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t}\n" + "\t\t\t\t}\n" + "\t\t\t],\n"
                + "\t\t\t\"disable_coord\": false,\n" + "\t\t\t\"adjust_pure_negative\": true,\n"
                + "\t\t\t\"boost\": 1\n" + "\t\t}\n" + "\t},\n" + "\t\"sort\": [\n" + "\t\t{\n"
                + "\t\t\t\"rcvTime\": {\n" + "\t\t\t\t\"order\": \"desc\"\n" + "\t\t\t}\n" + "\t\t}\n" + "\t]\n"
                + "}";
//        if (conditions.containsKey("id")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"id\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("id") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
//        if (conditions.containsKey("msgId")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"msgId\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("msgId") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
        if (conditions.containsKey("rcvTime")) {
            String times = (String) conditions.get("rcvTime");
            String startTime = times.substring(0, times.indexOf("-"));
            String endTime = times.substring((times.indexOf("-") + 1));
            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"range\": {\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"rcvTime\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"from\": "
                    + startTime + ",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"to\": " + endTime + ",\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"include_lower\": true,\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"include_upper\": true,\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
        }
        if (conditions.containsKey("serviceName")) {
            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"serviceName\": \""
                    + conditions.get("serviceName") + "\"\n \t\t\t\t\t\t\t\t\t\t\t} \n" + "\t\t\t\t\t\t\t\t\t\t}";
        }
        if (conditions.containsKey("tag")) {
            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match\": {\n"
                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"tag\": \""
                    + conditions.get("tag") + "\"\n\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
        }

//        if (conditions.containsKey("serviceName")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"serviceName\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("serviceName") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }

//        if (conditions.containsKey("resendFlag")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"resendFlag\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("resendFlag") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
//        if (conditions.containsKey("receiveSystem")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"receiveSystem\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("receiveSystem") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
//        if (conditions.containsKey("serviceState")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"serviceState\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("serviceState") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
//        if (conditions.containsKey("sendSystem")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"sendSystem\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("sendSystem") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
//        if (conditions.containsKey("connFlag")) {
//            queryParamJsons0 += ",{\n" + "\t\t\t\t\t\t\t\t\t\t\t\"match_phrase\": {\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\"connFlag\": {\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"query\": \""
//                    + conditions.get("connFlag") + "\",\n" + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"slop\": 0,\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t\t\t\"boost\": 1\n" + "\t\t\t\t\t\t\t\t\t\t\t\t}\n"
//                    + "\t\t\t\t\t\t\t\t\t\t\t}\n" + "\t\t\t\t\t\t\t\t\t\t}";
//        }
        queryParamJson = queryParamJsons1 + queryParamJsons0 + queryParamJsons2;
        return queryParamJson;
    }
}
